import os, sys
import json

"""
自动生成iconfont.xml的脚本
使用：
1 下载解压iconfont 文件
2.copy iconfont.ttf， iconfont.json 到 BasicApp/ui/src/main/res/font 目录下
3.执行iconfont.py脚本. eg: python ./script/iconfont.py
"""


def run():
    parentDir = ""
    iconfontJson = ""
    targetFilePath = ""
    if (len(sys.argv) > 1):
        parentDir = os.path.dirname(sys.argv[1])
        iconfontJson = os.path.join(parentDir, "iconfont.json")
        targetFilePath = os.path.join(parentDir, "iconfont.xml")
    else:
        parentDir = os.path.dirname(sys.path[0])
        targetFilePath = os.path.join(parentDir, "ui/src/main/res/values/iconfont.xml")
        iconfontJson = os.path.join(parentDir, "ui/src/main/res/font/iconfont.json")
    createIconfontString(iconfontJson, targetFilePath)

def createIconfontString(jsonFile, targetFile):
    print("generate start")
    if os.path.exists(targetFile):
        os.remove(targetFile)
    fontList = readIconfontJson(jsonFile)
    with open(targetFile, "w") as file:
        file.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
        file.write("<resources>\n")
        for item in fontList:
            file.write("\t<string name=\"%s\">%s</string>\n" % (item[0], item[1]))
        file.write("</resources>\n")
    os.remove(jsonFile)
    print("generate end")

def readIconfontJson(iconfontJson):
    fontList = []
    with open(iconfontJson, "r") as file:
        fontJson = json.loads(file.read())
        prefix = fontJson.get("css_prefix_text").replace("-", "_")
        glyphs = fontJson.get("glyphs")
        for item in glyphs:
            name = prefix + item.get("name").replace("-", "_")
            code = "&#x" + item.get("unicode") + ";"
            fontList.append([name, code])
    return fontList

if __name__ == '__main__':
    run()
